package com.gitbl.webchat.roomnode;

import com.alibaba.fastjson.JSONObject;
import com.gitbl.webchat.message.SpeakMessage;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.HashMap;
import java.util.Map;

public class Room {
    public String title;
    public String id;
    // 当前房间所有会话,用于群发
    private  ChannelGroup chgroup;
    //channleid --> userInfo map
    Map<String,UserInfo> users_channle;
    //username --> userinfo map
    Map<String,UserInfo> users_username;
    public Room(){
        chgroup=new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
        users_channle = new HashMap<>();
        users_username = new HashMap<>();
    }
    //用户加入房间
    public boolean add(UserInfo usr) {
        if(users_username.containsKey(usr.getUsername())){
            Channel oldc =users_username.get(usr.getUsername()).channel;
            chgroup.remove(oldc);
            users_channle.remove(oldc.id().asLongText());
            oldc.close();
            // todo send info to new channel;
            //
        }else{
            // todo send welcome to chgroup
            SpeakMessage m = new SpeakMessage();
            m.setSpeaker("all");
            m.setText("欢迎"+usr.getUsername()+"加入房间");
            TextWebSocketFrame f = new TextWebSocketFrame(JSONObject.toJSONString(m));
            chgroup.writeAndFlush(f);
        }
        SpeakMessage m = new SpeakMessage();
        m.setSpeaker("all");
        m.setText("欢迎"+usr.getUsername()+"加入房间");
        TextWebSocketFrame f = new TextWebSocketFrame(JSONObject.toJSONString(m));
        usr.channel.writeAndFlush(f);
        chgroup.add(usr.getChannel());
        users_channle.put(usr.getChannel().id().asLongText(),usr);
        users_username.put(usr.getUsername(),usr);
        return true;
    }

    public void SendAll(String username, String request) {
        SpeakMessage m = new SpeakMessage();
        m.setSpeaker(username);
        m.setText(request);
        TextWebSocketFrame f = new TextWebSocketFrame(JSONObject.toJSONString(m));
        chgroup.writeAndFlush(f);
    }

    public void leave(UserInfo u) {
        users_channle.remove(u.channel.id().asLongText());
        users_username.remove(u.getUsername());
        chgroup.remove(u.channel);
        SpeakMessage m = new SpeakMessage();
        m.setSpeaker("all");
        m.setText("用户"+u.getUsername()+"离开房间");
        TextWebSocketFrame f = new TextWebSocketFrame(JSONObject.toJSONString(m));
        chgroup.writeAndFlush(f);
    }
}
